package org.example;

public class test04 {
    //创建一个线程死锁
    static String a = "资源1";
    static String b = "资源2";

    public static void main(String[] args) {
        MyThread1 t1 = new MyThread1();
        t1.start();

        MyThread2 t2 = new MyThread2();
        t2.start();

    }

    private static class MyThread1 extends Thread {

        public MyThread1() {
            super("Thread1");
        }

        public void run() {
            //锁a
            //sleep
            //锁b
            //释放b
            //释放a

            //锁b
            //sleep
            //锁a
            //释放a
            //释放b

            synchronized (a) {
                final Thread thread = Thread.currentThread();

                System.out.println(thread.getName() + "占用a资源");

                try {
                    Thread.sleep(5000);
                } catch (Exception e) {

                }

                synchronized (b) {
                    System.out.println(thread.getName() + "占用b资源");
                }
            }
        }

    }

    private static class MyThread2 extends Thread {
        public MyThread2() {
            super("Thread2");
        }

        public void run() {
            synchronized (b) {
                final Thread thread = Thread.currentThread();
                System.out.println(thread.getName() + "占用b资源");

                try {
                    Thread.sleep(5000);
                } catch (Exception e) {

                }

                synchronized (a) {
                    System.out.println(thread.getName() + "占用a资源");
                }
            }
        }

    }
}
